import tkinter as tk
from tkinter import filedialog, messagebox
import json
import os


class ConfigEditorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("lockfile 配置编辑器")
        self.config_path = "config.json"
        self.config = self.load_config()

        # 列表数据绑定
        self.file_list = tk.Listbox(root, selectmode=tk.SINGLE, width=80, height=15)
        self.file_list.pack(padx=10, pady=10)

        # 按钮区域
        btn_frame = tk.Frame(root)
        btn_frame.pack(pady=5)

        self.add_button = tk.Button(btn_frame, text="添加文件", command=self.add_file)
        self.add_button.pack(side=tk.LEFT, padx=5)

        self.remove_button = tk.Button(btn_frame, text="删除选中", command=self.remove_selected)
        self.remove_button.pack(side=tk.LEFT, padx=5)

        self.save_button = tk.Button(btn_frame, text="保存配置", command=self.save_config)
        self.save_button.pack(side=tk.RIGHT, padx=5)

        # 初始化显示列表
        self.refresh_list()

        # 拖拽支持
        self.file_list.bind("<Button-3>", self.start_drag)
        self.file_list.bind("<B1-Motion>", self.drag_motion)
        self.file_list.bind("<ButtonRelease-1>", self.end_drag)

    def load_config(self):
        if not os.path.exists(self.config_path):
            messagebox.showerror("错误", f"找不到配置文件: {self.config_path}")
            return {"monitored_files": [], "backup_dir": "", "password_hash": ""}
        with open(self.config_path, 'r', encoding='utf-8') as f:
            return json.load(f)

    def refresh_list(self):
        self.file_list.delete(0, tk.END)
        for path in self.config["monitored_files"]:
            self.file_list.insert(tk.END, path)

    def add_file(self):
        files = filedialog.askopenfilenames(title="选择要监控的文件")
        if files:
            for file in files:
                if file not in self.config["monitored_files"]:
                    self.config["monitored_files"].append(file)
            self.refresh_list()

    def remove_selected(self):
        selected = self.file_list.curselection()
        if selected:
            index = selected[0]
            del self.config["monitored_files"][index]
            self.refresh_list()

    def save_config(self):
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=4, ensure_ascii=False)
            messagebox.showinfo("成功", "配置已保存！")
        except Exception as e:
            messagebox.showerror("保存失败", str(e))

    # 拖拽排序逻辑（简单实现）
    def start_drag(self, event):
        self.drag_start_index = self.file_list.nearest(event.y)

    def drag_motion(self, event):
        current_index = self.file_list.nearest(event.y)
        if current_index != self.drag_start_index and hasattr(self, 'drag_start_index'):
            item = self.file_list.get(self.drag_start_index)
            self.file_list.delete(self.drag_start_index)
            self.file_list.insert(current_index, item)
            # 更新 config 列表顺序
            self.config["monitored_files"].insert(current_index, self.config["monitored_files"].pop(self.drag_start_index))
            self.drag_start_index = current_index
            self.file_list.select_set(current_index)

    def end_drag(self, event):
        if hasattr(self, 'drag_start_index'):
            del self.drag_start_index


if __name__ == "__main__":
    root = tk.Tk()
    app = ConfigEditorApp(root)
    root.mainloop()
# pyinstaller --onefile --noconsole --icon=JSON.png --name "config"  file.py